#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File    :   GameMange
@Time    :   2023/03/08 20:40:45
@author  :   Eval
@Version :   1.0
@Describe:   编辑器使用, 用于管理资源,与正式游戏所需要的 GC 分离
'''
from json import loads as JsonLoads,dump as JsonWriteDump
from conf.GameLogin import *
import pygame

class Edit_GC:
    """供编辑器加载, 游戏使用 lib/下面的GC文件"""
    def __init__(self) -> None:
        # 加载资源注册文件
        self.SourceMgr = self.__loadFile("Source")
        # 加载全局脚本配置
        self.GC_Scripts = self.__loadFile("GlobalScript")

        self.MapImages = self.GC_Scripts["MapImages"]
        # 获取所有的地图名称
        self.MapNameList = self.GC_Scripts["FloorFiles"]
        self.LevelConf = self.GC_Scripts["LevelConf"]
        self.Hero = self.GC_Scripts["Hero"]

        # 全局游戏资源缓存字典,如果缓存字典里有这个图块的surface缓存,那么直接从缓存里面拿出来.避免多次执行操作影响性能,(ps:虽然用qt这玩意应该耗不了啥性能?)
        # 编辑器格式-->key : 图块类型-当前索引  or 图块类型-x-y
        self.GameSurfaceCache:dict[pygame.Surface] = {}

        # 缓存全局游戏事件的变量
        self.eventFlags:dict[str,str,int] = {}

    
    def __loadFile(self,fileName:str) -> dict:
        """加载资源文件"""
        data = None
        with open(f"conf/{fileName}.json",encoding="utf8") as f:
            data = JsonLoads(f.read())
        print_info(f"加载游戏脚本:{fileName}.json 完成")
        return data
    
    def saveGCScript(self) -> None:
        """编辑器调用,修改资源后保存"""
        with open(f"conf/GlobalScript.json","w",encoding="utf8") as file:
            JsonWriteDump(self.GC_Scripts,file,indent=4,ensure_ascii=False)
    
    def loadSurface(self,fileName:str):
        """根据图片名称加载缓存"""
        sourface = self.GameSurfaceCache.get(fileName)
        if sourface is None:
            sourface = pygame.image.load(f"lib/images/{fileName}")
            self.GameSurfaceCache[fileName] = sourface
        return sourface
    
    def getByPosSource(self,IKey:str):
        """根据传进来的索引返回当前坐标的图块信息"""
        return self.SourceMgr.get(str(IKey))